package nl.rainbowsheep.reisorg.empl.site.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import nl.rainbowsheep.reisorg.empl.site.authentication.BasicAuthInterceptor;
import nl.rainbowsheep.reisorg.empl.site.model.Trip;
import nl.rainbowsheep.reisorg.empl.site.viewmodel.TripViewmodel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class TripService {

    @Value("${api.url}")
    String url;

    public List<TripViewmodel> getAll() {
        RestTemplate template = new RestTemplate();
        final List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
        interceptors.add(new BasicAuthInterceptor());
        template.setInterceptors(interceptors);
        TripViewmodel[] models = template.getForObject(url + "trip/getall?predefined=true" + "&" + getLocaleParam(), TripViewmodel[].class);
        return Arrays.asList(models);
    }

    public TripViewmodel getById(long id) {
        RestTemplate template = new RestTemplate();
        final List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
        interceptors.add(new BasicAuthInterceptor());
        template.setInterceptors(interceptors);
        TripViewmodel trip = template.getForObject(url + "/trip/gettrip?id=" + id + "&" + getLocaleParam(), TripViewmodel.class);
        return trip;
    }

    //WAT IS DIT!??????
    public Trip insertTripViewmodel(TripViewmodel tripViewmodel) {
        RestTemplate template = new RestTemplate();
        final List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
        interceptors.add(new BasicAuthInterceptor());
        template.setInterceptors(interceptors);
        return template.postForObject(url + "trip/save", tripViewmodel, Trip.class);
    }

    public Trip save(Trip trip) {
        RestTemplate template = new RestTemplate();
        final List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
        interceptors.add(new BasicAuthInterceptor());
        template.setInterceptors(interceptors);
        return template.postForObject(url + "trip/save", trip, Trip.class);
    }

    /**
     * Get current locale (from cookie)
     *
     * @return string with locale param
     */
    private String getLocaleParam() {
        return "locale=" + LocaleContextHolder.getLocale().getLanguage();
    }

}
